import re
import requests
from time import sleep
from selenium import webdriver
from selenium.webdriver import Chrome
from selenium.webdriver import ChromeOptions
import time
# options = webdriver.FirefoxOptions()
option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
# options.add_argument('-headless')
# driver = webdriver.Firefox(options=options)
driver = Chrome(options=option)

#代理池
def get_proxy():
    abc = requests.get("http://127.0.0.1:5010/get/").text
    print(abc)
    return abc

def writetxt(msg, type):
    # print(request.META)
    if type == 1:
        try:
            with open('links1.txt', 'a+', encoding='utf-8') as f:
                f.write(msg + '\n')
        except:
            pass
    elif type == 2:
        try:
            with open('links1.txt', 'a+', encoding='utf-8') as f:
                f.write(msg + '\n')
        except:
            pass
    elif type == 3:
        try:
            with open('丢弃的词汇.txt', 'a+', encoding='utf-8') as f:
                f.write(msg + '\n')
        except:
            pass


def matchword(content, keyword):
    abc= re.compile(fr'<em><!--red_beg--{keyword}<!--red_end--></em></a>, re.I')
    myvalue = re.search(abc, content)
    print(myvalue)
    if myvalue == None:
        # 丢弃
        return False
    else:
        #匹配到公众号
        return "匹配到公众号"

def matchwx(content, keyword):
    wxh= re.compile(fr'<p class="info">微信号：<label name="em_weixinhao">{keyword}</label>, re.I')
    myvalue = re.search(wxh, content)
    # print(myvalue)
    if myvalue == None:
        # 丢弃
        return False
    else:
        #匹配到微信号
        return "匹配到微信号"

def readtxt():
    wordlist = []
    for line in open("keywords.txt", encoding='utf-8'):
        wordlist.append(line.strip())
    print(wordlist)
    return wordlist



def geturl(keyword):
    url = f'https://weixin.sogou.com/weixin?type=1&s_from=input&query={keyword}&ie=utf8&_sug_=n&_sug_type_='
    return url

#保存和返回cookie
def savecookie(driver):
    # print(driver.get_cookies())
    cookie = [item["name"] + "=" + item["value"] for item in driver.get_cookies()]
    cookiestr = '; '.join(item for item in cookie)
    f = open("sougoucookie.txt", 'wb')
    f.write(cookiestr.encode('utf-8'))
    f.close()
    return cookiestr

def upload():
    listuser = readtxt()
    url = f'http://www.tbzhu.com/admingetpost/?username="{listuser}"'
    requests.get(url)


#判断内容是否是限制




# headers={
#     'cookie':,
#     'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36'
# }
upload()
sleep(5)
for keyword in readtxt():
    # time.sleep(10)
    print(keyword)
    # print(f"{i}关键词是否有用")
    index = driver.get(geturl(keyword))
    driver.implicitly_wait(1)
    #获取内容
    content = driver.page_source
    searchvalue = re.search(keyword, content)
    serach = re.search('请输入图中的验证码', content)
    print(content)
    if serach != None:
    # 搜狗限制网页，等待输入验证码
        print('搜狗限制网页，等待验证码输入成功后开启')
        # print(content)
        SUsername = input("请确认验证码已成功开启，按任意字符回车继续")
    content = driver.page_source
    searchvalue = re.search(keyword, content)
    if searchvalue != None:
        if matchword(content, keyword) == '匹配到公众号':
            writetxt(keyword, 1)
        elif matchwx(content, keyword) == '匹配到微信号':
            writetxt(keyword, 2)
        else:
            writetxt(keyword, 3)
